import mapboxgl from "mapbox-gl";
import store from "../../store/index.js";
import http from "@/utils/request.js";
mapboxgl.accessToken = "pk.eyJ1Ijoid3p5YW5ndXN0IiwiYSI6ImNsZ21iemNrdzAzN2gzaHM5ZnIxcmZzOWoifQ.gFp9hXXjG9vBdd2K-Wv2fw";
// Haversine公式算法: 根据经纬度计算距离
//(lon为经度,lat为纬度)
const Haversine = (lon1, lat1, lon2, lat2) => {
  Number.prototype.deg2rad = function (deg) {
    return deg * (Math.PI / 180);
  };
  var dLat = (0).deg2rad(lat2 - lat1);
  var dLon = (0).deg2rad(lon2 - lon1);
  var a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos((0).deg2rad(lat1)) *
    Math.cos((0).deg2rad(lat2)) *
    Math.sin(dLon / 2) *
    Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return c * 6378;
};

export const text100 = () => {
  var city = {
    雁门关: true,
  };
  var markers = [];
  var messages = [];
  //在这里读取本地JSON文件
  var mainCity;
  var Chronology;
  var data3;
  http.get('/user/map').then(res=>{
    mainCity=res.data.mainCity;
    Chronology=res.data.Chronology
    data3=res.data.data3
  })
  const map = new mapboxgl.Map({
    container: "map",
    // 从地图盒的核心样式中进行选择，或使用地图盒工作室制作自己的样式
    style: "mapbox://styles/wzyangust/clpcmno2c00ae01p99jd8910q",
    pitch: 20, // 设置倾斜程度
    center: [103.8, 30.4],
    zoom: 7,
  });



  map.loadImage("picture/figureImage/李白.png", (error, image) => {
    if (error) throw error;
    if (!map.hasImage("locusImage")) {
      map.addImage("locusImage", image);
    }
  });
  map.on('styleimagemissing', async (e) => {
    let el = new Image(100,100);
    el.className = 'marker';
    el.src = await "picture/figureImage/李白.png";
    map.addImage(e.id, el);
  });



  map.on("load", async () => {
    // 向地图添加缩放和旋转控件, 默认为右上角
    map.addControl(new mapboxgl.NavigationControl());
    // 向地图添加比例尺, 默认左下角
    map.addControl(new mapboxgl.ScaleControl({ maxWidth: 75, unit: "metric" }));
    // 向地图添加全屏按钮,默认右上角
    map.addControl(new mapboxgl.FullscreenControl());

    // 定义源数据
    let point = {
      type: "FeatureCollection",
      features: [
        {
          type: "Feature",
          properties: {
            bearing: 0,
            name: "",
          },
          geometry: {
            type: "Point",
            coordinates: [104.732, 31.774],
          },
        },
      ],
    };
    let data = {
      type: "FeatureCollection",
      features: [
        {
          type: "Feature",
          geometry: {
            type: "LineString",
            coordinates: [[104.732, 31.774]],
          },
        },
      ],
    };
    // 处理数据
    // 处理显示的城市
    for (let key in mainCity) {
      for (let i in mainCity[key]) {
        city[mainCity[key][i]] = true;
      }
    }
    // 添加点位
    var startTime = store.state.timeline;

    var startI = 0,
      currentI = 0;
    var startJ = 0;
    for (let i = 0; i < data3.length; i++) {
      if (data3[i][2] == startTime) {
        startI = currentI;
        startJ = i;
        startTime = 123;
      }
      if (i == 0) {
        for (let j = 1; j <= 20; j++) {
          data.features[0].geometry.coordinates.push([
            data3[i][0] + (Math.random() % 0.02) - 0.01,
            data3[i][1] + (Math.random() % 0.02) - 0.01,
          ]);
          currentI++;
        }
      } else {
        let lon1 = data3[i - 1][0];
        let lon2 = data3[i][0] - data3[i - 1][0];
        let lat1 = data3[i - 1][1];
        let lat2 = data3[i][1] - data3[i - 1][1];
        let distance = turf.distance(
          turf.point([data3[i - 1][0], data3[i - 1][1]]),
          turf.point([data3[i][0], data3[i][1]]),
          { units: "kilometers" }
        );
        let n = parseInt(distance / 2.8);
        for (let j = 1; j <= n; j++) {
          if (j == 1) data.features[0].geometry.coordinates.push([lon1, lat1]);
          else
            data.features[0].geometry.coordinates.push([
              lon1 + (Math.random() % 0.02) - 0.01,
              lat1 + (Math.random() % 0.02) - 0.01,
            ]);
          lon1 += lon2 / n;
          lat1 += lat2 / n;
          currentI++;
        }
      }
    }
    // 初始点
    let i = startI,
      j = startJ;
    if (startI != 0) i--;
    if (startJ != 0) j--;
    store.state.currentProgress = i;
    // 设置视口
    const coordinates = data.features[0].geometry.coordinates;
    data.features[0].geometry.coordinates = [coordinates[i]];
    point.features[0].geometry.coordinates = coordinates[i];

    if (i < coordinates.length && i > 25) {
      for (let j = 1; j < i; j++) {
        let dist = turf.distance(
          turf.point(coordinates[j]),
          turf.point(coordinates[j - 1]),
          { units: "kilometers" }
        );
        store.state.kilometer += Number(
          String(dist).replace(/^(.*\..{2}).*$/, "$1")
        );
        store.state.kilometer = Number(
          String(store.state.kilometer).replace(/^(.*\..{2}).*$/, "$1")
        );
      }
    }

    map.jumpTo({ center: coordinates[i], zoom: 7.2 });
    map.setPitch(20);

    map.addSource("trace", { type: "geojson", data: data });
    map.addSource("point", { type: "geojson", data: point });
    //这里是读取移动线条的属性
    map.addLayer({
      id: "trace",
      type: "line",
      source: "trace",
      paint: {
        // 'line-color': "#737cbd",
        "line-color": "#303030",
        "line-opacity": 0.8,
        "line-width": 8,
      },
    });


    map.addLayer({
      id: "point",
      source: "point",
      type: "symbol",
      layout: {
        // 此图标是地图框街道样式的一部分。
        // 要查看Mapbox样式中可用的所有图像，请在Mapbox Studio中打开该样式，然后单击“图像”选项卡。
        // 要在运行时向样式添加新图像，请参阅 https://docs.mapbox.com/mapbox-gl-js/example/add-image/
        "icon-image": "locusImage",
        "icon-size": 0.2,
        "icon-rotate": ["get", "bearing"],
        "icon-rotation-alignment": "map",
        "icon-allow-overlap": true,
        "icon-ignore-placement": true,
        "text-field" : "前往{name}",
        'text-offset':[2, 2],
        // 'text-anchor':'top',
        'text-size': 14
      },
      paint: {
        "text-color": 'rgba(255,0,255,1)'
      }
    });



    store.state.isclose = false;
    store.state.currentRouter = 3;

    // 动画跑图
    const timer = setInterval(() => {
      if (store.state.isclose) {
        for (let k = 0; k < markers.length; k++) {
          markers[k].remove();
        }
				for(let k=0;k< messages.length;k++) {
					messages[k].remove();
				}
				
        map.removeLayer("point");
        map.removeSource("point");
        map.removeLayer("trace");
        map.removeSource("trace");
        store.state.currentProgress = 0;
        window.clearInterval(timer);
      } 
      else if (store.state.currentRouter != 3) {
        store.state.currentProgress = 0;
        window.clearInterval(timer);
      } 
      else if (store.state.isPause) {
        if (i < coordinates.length && j < data3.length) {
          data.features[0].geometry.coordinates.push(coordinates[i]);
          map.getSource("trace").setData(data);


          point.features[0].geometry.coordinates = coordinates[i];
          point.features[0].properties.name = data3[j][3];

          map.getSource("point").setData(point);
          

          // 排除后续插入点(双指针查找算法)
          if (coordinates[i][0] == data3[j][0]) {
            // 诗词提及地点
            if (city[data3[j][3]] == true) {
              let points = coordinates[i]; // 捕获结果坐标
              point.features[0].properties.name = data3[j][3];

              let geojson = [{
                'icon': 'picture/mapbox/点位图外透明.png',
                'coordinates' : points
              }]

              for(var item of geojson) {
                let el = document.createElement('div');
                el.className = 'marker';
                el.textContent = "啊啊啊啊啊啊啊啊啊";
                el.classList.add('marker')
                el.style.background = "white";
                el.style.height = '50px';
                el.style.width = '50px';
                el.style.borderRadius = '50px';
                el.style.opacity = '0';
                el.style.animation = 'fade-in 1s ease-in-out forwards';
                markers.push(
                  new mapboxgl.Marker(el)
                    .setLngLat(points)
                    .addTo(map)
                );
                // markers[markers.length-1].getElement().style.animation = 'fade-in 5s ease-in-out forwards';
                // markers[markers.length-1].getElement().style.opacity = 1; 
              }

              // let el = document.createElement("div");
              // el.className = "marker";
              // el.style.backgroundImage = `url(picture/mapbox/点位图外透明.png)`;
              // el.style.width = `100px`;
              // el.style.height = `75px`;
              // el.style.backgroundSize = "40%";
              // el.style.backgroundRepeat = "no-repeat";
              // el.style.backgroundPosition = "center";
              // 添加标记
              // markers.push(
              //   new mapboxgl.Marker(el, { rotationAlignment: "map" })
              //     .setLngLat(points)
              //     .addTo(map)
              // );
							if(data3[j][4] != "《非诗词,过渡用》") {
                let sjsjsj = 1;
								// messages.push(
								// 	new mapboxgl.Popup({ 
                //       offset: [0, 0],
                //       closeOnClick: false,
                //       closeButton: false,
                //       maxWidth: 'none'
                //     })
								// 		.setLngLat(points)
								// 		.setHTML(
								// 			"<div style='width: 17.5vw;height: 10vh;display:flex; flex-direction: column;justify-content: space-around;line-height: 4vh'>" +
								// 				"<div style='font-size:2.3vh;font-family:楷体;font-weight:900;'>" + "地点: " + data3[j][3] + "</div>" +
								// 				"<div style='font-size:2.3vh;font-family:楷体;font-weight:900;'>" + "该年主要诗词: " + data3[j][4] + "</div>" +
								// 			"</div>"
								// 		)
								// 		.addTo(map)
								// );
							}
            }
            for (let k = 0; k < markers.length; k++) {
              if (
                Haversine(
                  markers[k].getLngLat().lng,
                  markers[k].getLngLat().lat,
                  coordinates[i][0],
                  coordinates[i][1]
                ) > 250
              ) {
                markers[k].remove();
              }
            }
            for (let k = 0; k < messages.length; k++) {
              if (
                Haversine(
                  messages[k].getLngLat().lng,
                  messages[k].getLngLat().lat,
                  coordinates[i][0],
                  coordinates[i][1]
                ) > 75
              ) {
                messages[k].remove();
              }
            }
            j++;
            store.state.time = data3[j][2];
            store.state.year = Chronology[store.state.time].time;
            store.state.things = Chronology[store.state.time].events;
          }
          map.panTo(coordinates[i]);
          i++;
          store.state.currentProgress++;

          // 实时更新里程数
          if (i < coordinates.length && i > 25) {
            let dist = turf.distance(
              turf.point(coordinates[i]),
              turf.point(coordinates[i - 1]),
              { units: "kilometers" }
            );
            store.state.kilometer += Number(
              String(dist).replace(/^(.*\..{2}).*$/, "$1")
            );
            store.state.kilometer = Number(
              String(store.state.kilometer).replace(/^(.*\..{2}).*$/, "$1")
            );
          }
        } else {
          for (let k = 1; k < markers.length; k++) {
            markers[k].remove();
          }
					for(let k=1;k< messages.length;k++) {
						messages[k].remove();
					}
          map.removeLayer("point");
          map.removeSource("point");
          window.clearInterval(timer);
        }
      }
      else { 
        // map.removeSource("point");
        map.removeLayer("point");
        map.addLayer({
          id: "point",
          source: "point",
          type: "symbol",
          layout: {
            // 此图标是地图框街道样式的一部分。
            // 要查看Mapbox样式中可用的所有图像，请在Mapbox Studio中打开该样式，然后单击“图像”选项卡。
            // 要在运行时向样式添加新图像，请参阅 https://docs.mapbox.com/mapbox-gl-js/example/add-image/
            "icon-image": "locusImage",
            "icon-size": 0.2,
            "icon-rotate": ["get", "bearing"],
            "icon-rotation-alignment": "map",
            "icon-allow-overlap": true,
            "icon-ignore-placement": true,
            "text-field" : "前往{name}",
            'text-offset':[2, 2],
            // 'text-anchor':'top',
            'text-size': 14
          },
          paint: {
            "text-color": 'rgba(255,0,255,1)'
          }
        });
      }
    }, 40);
  });
};
